<template>
  <div style="width:90%;">
    <el-button @click="goback()" size="mini" type="primary" style="margin-left:1000px">返回</el-button>
    <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px" :disabled="this.$route.params.bukan">

      <el-input v-model="planForm.uuid" type="hidden"></el-input>
      <el-input v-model="planForm.orgSeq" type="hidden"></el-input>
      <el-form-item label="礼品类型:" prop="giftType">
        <el-select v-model="planForm.giftType">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="礼品名称:" prop="giftName" >
        <el-input
          v-model="planForm.giftName"
          :disabled="disabledFlag"
          style="width:360px;"
          placeholder="请输入奖品名称"
          maxlength="30"
          show-word-limit
        ></el-input>
      </el-form-item>

      <!-- <el-form-item label="优惠券：" prop="planCouponList" v-if="planForm.prizeType =='1'">
          <el-table
              :data="planCouponList"
              @selection-change="planCouponChecked"
              border
              style="font-size: 10px;width:70%;"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column
                  prop="couponName"
                  label="优惠券名称"
                  width="200"
                  header-align="center"

              ></el-table-column>
              <el-table-column
                  prop="couponSeq"
                  label="优惠券编号"
                  width="150"
                  header-align="center"
              ></el-table-column>
              <el-table-column
                  prop="couponMoney"
                  label="优惠券面值"
                  width="150"
                  header-align="center"
                  align="left"
              >
                  <template slot-scope="scope">
                      <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
                  </template>
              </el-table-column>
              <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
          </el-table>
          <div style="margin-top:10px;">
              <el-button
                  type="primary"
                  @click="selectCoupon('planForm')"
                  v-if="!disabledFlag"
              >选择卡券</el-button> -->
      <!-- <el-button @click="deleteCoupon('planForm')" v-if="!disabledFlag">删除卡券</el-button> -->
      <!-- </div>
  </el-form-item> -->

      <el-form-item label="礼品主图:" prop="imgListone">
        <image-upload v-model="planForm.imgListone" :size="'400x400'" :limit="1"></image-upload>
        <p class="tips" style="margin-left: 10px;color:red;">图片将用于消费者端商品列标图</p>
      </el-form-item>
      <el-form-item label="礼品轮播图:" prop="imgListtwo">
        <image-upload v-model="planForm.imgListtwo" :size="'400x400'" ></image-upload>
        <p class="tips" style="margin-left: 10px;color:red;">图片将用于消费者端礼品详情图页轮播图</p>
      </el-form-item>
      <el-form-item label="详情图片:" prop="imgListthree">
        <image-upload v-model="planForm.imgListthree" :size="'400x400'" :limit="1"></image-upload>
        <p class="tips" style="margin-left: 10px;color:red;">图片将用于消费者端礼品详情图页</p>
      </el-form-item>
      <el-form-item label="礼品详情:" prop="giftDesc">
        <el-input
          type="textarea"
          v-model="planForm.giftDesc"
          :disabled="disabledFlag"
          placeholder="请输入奖品说明"
          maxlength="120"
          show-word-limit
          :autosize="{minRows:2}"
          style="width:650px;"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="!this.$route.params.bukan">
        <el-button type="primary" @click="submitForm('planForm')" v-if="!disabledFlag">保 存</el-button>
        <el-button @click="resetForm('planForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-dialog title="选择优惠券" :visible.sync="dialogVisibleCoupon" width="55%">
        <el-form
            :inline="true"
            :model="formCoupon"
            class="search-form-inline"
            style="margin-top:-20px;"
        >
            <el-input v-model="formCoupon.couponName" style="width:200px;" placeholder="优惠券名称"></el-input>
            <el-button
                type="primary"
                size="mini"
                icon="el-icon-search"
                @click="getCouponList()"
            >查询</el-button>
        </el-form>
        <el-table
            ref="singleTable"
            :data="couponList"
            @selection-change="couponChecked"
            border
            style="font-size: 10px;width:100%;"
            height="300"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column
                prop="couponName"
                label="优惠券名称"
                width="200"
                header-align="center"

            ></el-table-column>
            <el-table-column prop="couponSeq" label="优惠券编号" width="150" header-align="center"></el-table-column>
            <el-table-column prop="couponMoney" label="优惠券面值" width="150" header-align="center">
                <template slot-scope="scope">
                    <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
                </template>
            </el-table-column>
            <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisibleCoupon = false">取 消</el-button>
            <el-button
                type="primary"
                @click="couponConfirm()"
                :disabled="this.lsCouponList.length!=1"
            >确 定</el-button>
        </span>
    </el-dialog> -->
  </div>
</template>
<script>
  // import {
  //     addPrize,
  //     updatePrize,
  //     queryGenCoupon
  // } from "@/api/prizeLibrary";
  import {
    addPrize,
    updatePrize,
    queryGenCoupon
  } from "@/api/pointsGiftBank";
  import {
    queryPromotionList,
    queryPromotionById,
    queryCouponById,
    savePromotion,
    updatePromotionStatus,
    createTPlan
  } from "@/api/promotionProgramEdit";
  import imageUpload from "@/page/common/Image-upload";
  import { queryCouponList } from "@/api/promotionProgramEdit";

  export default {
    data() {
      return {
        keepAlive:true,
        logininfo: {},
        orgList: [],
        orgSeq: "",
        loading: true,
        typeOptions: [
          // {value: "1",label: '虚拟奖品'},
          {value: "1",label: '实物礼品'}],
        lsPlanCouponList: [],
        lsCouponList: [],
        planCouponList: [],
        couponList: [],
        planForm: {
          uuid: "",
          giftType: "",
          giftName: "",
          giftDesc: "",
          // beginTime: "",
          // endTime: "",
          // status: "",
          // promotionCouponInfo: [],
          imgListone: [],
          imgListtwo: [],
          imgListthree: [],
          giftMainPic:"",
          giftRunPic:"",
          giftDetailPic:"",

        },
        formCoupon: {
          couponName: ""
        },
        dialogVisibleCoupon: false,
        disabledFlag: false,
        listQuery: {
          current: 1,
          size: 10
        },
        total: 0,
        planRules: {

          giftName: [{ required: true, message: "请输入礼品名称", trigger: "blur" }],
          giftType: [{ required: true, message: "请输入礼品类型", trigger: "blur" }],
          imgListone: [{ required: true, message: "请输入礼品主图", trigger: "blur" }],
          imgListtwo: [{ required: true, message: "请输入礼品轮播图", trigger: "blur" }],
          imgListthree: [{ required: true, message: "请输入详情图片", trigger: "blur" }],
          giftDesc: [{ required: true, message: "请输入礼品详情", trigger: "blur" }],
        }
      };
    },
    components: {
      imageUpload
    },
    mounted() {
      this.logininfo = localStorage.getItem("logininfo");
      this.orgList = JSON.parse(this.logininfo).orgList;
      this.orgSeq = this.orgList[0].orgSeq;
      this.planForm.orgSeq = this.orgList[0].orgSeq;

      var v = this.$route.params.edit;
      if (v) {
        // 修改，回显值
        this.planForm.uuid = v.uuid;
        this.planForm.giftName = v.giftName;
        this.planForm.giftType = String(v.giftType);
        this.planForm.prizePicture = v.prizePicture;
        this.planForm.couponId = v.couponId;
        // this.planCouponList = res.result.promotionCouponInfo;
        this.planForm.imgListone = v.giftMainPic == null || v.giftMainPic == ""?[]:[v.giftMainPic];
        this.planForm.imgListtwo = v.giftRunPic
        this.planForm.imgListthree = v.giftDetailPic == null || v.giftDetailPic == ""?[]:[v.giftDetailPic];
        this.planForm.giftDesc = v.giftDesc;
        this.planForm.beginTime = v.beginTime;
        this.planForm.endTime = v.endTime;
        this.planForm.status = v.status;

        this.queryPromotionById(v.couponId);
      } else {
        // 新增，默认值
        this.planForm.uuid = "";
        this.planForm.status = "1";
        this.getCouponList();
      }
    },
    methods: {
      goback() {
        this.$router.go("-1");
      },
      quantityBlur(e, idx) {
        if (e.target.value == '') { return; }
        let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
        if (!flag) {
          this.$message({
            message: "限领数量请输入正整数",
            type: "warning"
          });
          e.target.value = '';
        }
      },
      numberBlur(e, name) {
        if (e.target.value == "") {
          return;
        }
        let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
        if (!flag) {
          this.$message({
            message: name + "请输入正整数",
            type: "warning"
          });
          e.target.value = "";
        }
      },
      queryPromotionById(uuid) {
        let data = {
          size: 100,
          current: 1,
          condition: {
          },
          ascs: [],
          descs: []
        };
        queryGenCoupon(data).then(res => {
          if (
            res.records != null &&
            res.records.length > 0
          ) {
            // this.planCouponList =res.records;
            // 去掉已选的
            for (var i in res.records) {
              console.log(uuid);
              console.log(res.records[i]);
              if(uuid == res.records[i].uuid){
                this.planCouponList.push(res.records[i]);
              }
            }

          }
          this.getCouponList();
        });
        this.loading = false;
      },

      getCouponList() {
        let data = {
          size: 100,
          current: 1,
          condition: {
            status: 1,
            couponType: 1,
            keyWord: this.formCoupon.couponName
          },
          ascs: [],
          descs: []
        };
        queryGenCoupon(data).then(res => {
          this.couponList = res.records;
          // 去掉已选的
          for (var i in this.planCouponList) {
            this.removeByValue(
              this.couponList,
              "uuid",
              this.planCouponList[i].uuid
            );
          }
        });
        this.loading = false;
      },

      planCouponChecked(row) {
        this.lsPlanCouponList = row;
      },
      couponChecked(row) {
        this.lsCouponList = row;
        if (this.lsCouponList.length > 1) {
          this.$refs.singleTable.toggleRowSelection(this.lsCouponList[0]);
        }
      },
      selectCoupon() {
        // 显示选择卡券对话框
        this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      },
      deleteCoupon() {
        // 删除已选择的卡券
        this.couponList = this.couponList.concat(this.lsPlanCouponList);
        for (var i in this.lsPlanCouponList) {
          this.removeByValue(
            this.planCouponList,
            "uuid",
            this.lsPlanCouponList[i].uuid
          );
        }
      },
      couponConfirm() {
        this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
        this.planCouponList = this.lsCouponList;//this.planCouponList.concat(this.lsCouponList);
        // for (var i in this.lsCouponList) {
        //   this.removeByValue(this.couponList, "uuid", this.lsCouponList[i].uuid);
        // }
      },

      submitForm(formName) {
        // 保存奖品

        if (this.planForm.giftType == "" || this.planForm.giftType == null) {
          this.$message.error("请选择礼品类型");
          return;
        }
        if (this.planForm.giftName == "" || this.planForm.giftName == null) {
          this.$message.error("请输入礼品名称");
          return;
        }
        if (this.planForm.imgListone.length == 0) {
          this.$message.error("请上传礼品主图");
          return;
        }
        if (this.planForm.imgListtwo.length == 0) {
          this.$message.error("请上传礼品轮播图");
          return;
        }
        if (this.planForm.imgListthree.length == 0) {
          this.$message.error("请上传详情图片");
          return;
        }
        if (this.planForm.giftDesc == "" || this.planForm.giftDesc == null) {
          this.$message.error("请输入礼品详情");
          return;
        }
        // if (this.planForm.prizeType=="1" && this.planCouponList.length != 1) {
        //   this.$message.error("请选择1张卡券,多余的请删除");
        //   return;
        // }
        // for (var i in this.planCouponList) {
        // 删除提交时不需要的属性或容易导致错误的属性
        //   if (
        //     this.planCouponList[i].couponId != null &&
        //     this.planCouponList[i].couponId != undefined
        //   ) {
        //     this.planCouponList[i].couponId = this.planCouponList[i].uuid;
        //   }
        //   delete this.planCouponList[i].createTime;
        //   delete this.planCouponList[i].createUser;
        //   delete this.planCouponList[i].updateTime;
        //   delete this.planCouponList[i].updateUser;
        //   delete this.planCouponList[i].beginTime;
        //   delete this.planCouponList[i].endTime;
        //   delete this.planCouponList[i].comments;
        //   delete this.planCouponList[i].validCreateDate;
        //   delete this.planCouponList[i].validEndDate;
        // }
        // this.planForm.promotionCouponInfo = this.planCouponList;
        // if (this.planForm.prizeType=="1"){
        // this.planForm.couponId = this.planForm.promotionCouponInfo[0].uuid;
        // this.planForm.prizeName = this.planForm.promotionCouponInfo[0].couponName;
        // }

        this.planForm.giftMainPic = this.planForm.imgListone[0]
        this.planForm.giftRunPic = this.planForm.imgListtwo
        console.log( this.planForm.giftRunPic,"uiuug")
        this.planForm.giftDetailPic = this.planForm.imgListthree[0]
        this.keepAlive = false;
        console.log(this.planForm);
        if(this.planForm.uuid == ""){
          this.planForm.uuid = null
          addPrize(this.planForm).then(res => {
            if (res.code == "1") {
              this.$message({
                showClose: true,
                message: "保存成功",
                type: "success"
              });
              this.$router.push("pointsGiftBank");
            } else {
              this.$message({
                showClose: true,
                message: "保存失败",
                type: "success"
              });
            }
          });
        } else {
          updatePrize(this.planForm).then(res => {
            if (res.code == "1") {
              this.$message({
                showClose: true,
                message: "修改成功",
                type: "success"
              });
              this.$router.push("pointsGiftBank");
            } else {
              this.$message({
                showClose: true,
                message: "修改失败",
                type: "success"
              });
            }
          });
        }
      },
      // 数组，属性，属性值
      removeByValue: function(arr, attr, value) {
        if (arr == null) {
          return;
        }
        var index = 0;
        for (var i in arr) {
          if (arr[i][attr] == value) {
            index = i;
            break;
          }
        }
        arr.splice(index, 1);
      },
      handleRemove(file, fileList) {
        let newfileList = [];
        fileList.forEach((item, i) => {
          let data = {
            name: item.name,
            url: item.url
          };
          newfileList.push(data);
        });
        this.fileList = newfileList;
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.$router.push("pointsGiftBank");
      }
    },
    beforeRouteLeave(to, from, next) {
      // 设置下一个路由的 meta
      to.meta.keepAlive = this.keepAlive; // C 跳转到 A 时让 A 不缓存，即刷新
      next();
    },
  };
</script>
<style lang="less" scoped>
  .el-col-20 {
    border: 1px solid #ebeef5;
    margin-left: 150px;
    width: 60%;
  }
  .el-input {
    width: 60%;
  }
  .search-form-inline {
    border: 1px solid #ebeef5;
    line-height: 30px;
    padding: 12px;
    margin-bottom: 5px;
  }
  thead {
    .el-table-column--selection {
      .cell {
        display: none;
      }
    }
  }
  .tips {
    width: max-content;
    font-size: 12px;
    line-height: normal;
    color: #999999;
    margin-top: 5px;
  }
</style>
